<?php

class CopyLive extends Controller{
	var $staging_db = "mydomains_jrs_staging";
	var $live_db = "mydomains_jrs";
	
	var $staging_uploads = '/var/www/vhosts/jrsarchitect.com/subdomains/staging/httpdocs/uploads';
	var $live_uploads = '/var/www/vhosts/jrsarchitect.com/subdomains/staging/httpdocs/uploads_copy_test';
	
	var $db_backup_dir = '/var/www/vhosts/jrsarchitect.com/subdomains/staging/httpdocs/dbbackup';
	var $db_backup_filename = 'mydomains_jrs.backup.sql';
	
	function CopyLive(){
		parent::Controller();
		$this->load->database();
		$this->load->dbutil();
		$this->load->helper('file');
		$this->load->library('html');
		$this->load->helper('url');
	}
	
	function index(){
		$this->load->view('admin/copy_live_confirm');
	}
	
	function executeCopy(){
		if( strtolower($this->input->post('submit')) == 'continue'){
			$this->_copyDatabase();
			$this->_copyUploads();
			$this->load->view('admin/copy_live_success');
		}else{
			redirect('/admin/');
		}
	}
	
	function _copyDatabase(){
		/* get the contents of the staging database */
		$data =& $this->dbutil->backup(
			array(
				'format'	=> 'text'
			)
		);
		
		/* create a backup of the current live database */
		$live = $this->load->database('live', true);
		if( $this->db_backup_dir && create_path($this->db_backup_dir)){
			$ci =& get_instance();
			$db = $ci->db;
			$ci->db = $live;
			$backup =& $this->dbutil->backup(
				array(
					'filename' => $this->db_backup_filename
				)
			);
			write_file( $this->db_backup_dir . '/db.backup.gz', $backup);
			$ci->db = $db;
		}
		
		$queries = explode(";\n", $data);
		foreach($queries as $query){
			$query = trim($query);
			$query = preg_replace(
				array(
					"/#(.*)\n/",
					"/^[\s]*\n/"
				),
				array(
					"",
					""
				),
				$query
			);
			if( !empty($query) ){
				$live->query($query);
			}
		}
	}
	
	function _copyUploads(){
		if( create_path($this->staging_uploads) && create_path($this->live_uploads)){
			copy_directory($this->staging_uploads, $this->live_uploads);
		}
	}
}

?>
